<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Hash;
class LoginController extends Controller
{
    /** getIndex() 前台登录页面
     * 
     *
     * @return('welcome') 返回前台首页视图
     */
    public function getIndex(){
        return view('home.login.index');
    }


    /**
     * dologin() 前台登录验证
     * 
     * @param   $data  array    接收传过来的数据
     * @param   $res1  string   哈希解密验证密码
     * @param   
     * @return  跳转前台首页视图
     */
    public function postDologin(Request $request){
    	$data = $request -> all();
    	// 验证验证码是否一致
    	if(session('code') != $request -> input('code')){  		
			return back() -> withInput()-> with('error','抱歉:验证码错误');  		
		}
		// 验证帐号是否存在
    	$res = DB::table('users') -> where('user_phone',$data['user_phone']) -> orwhere('user_email',$data['user_phone']) -> first();       
    	// 验证密码
    	$res1 = Hash::check($request -> input('password'),$res['user_pass']);       	
    	if($res1 && $res){
    		// 将帐号登录时间写入数据库
    		$arr['user_time'] = date('Y-m-d H:i:s',time());
    		DB::table('users') -> where('user_phone',$data['user_phone']) -> orwhere('user_email',$data['user_phone']) -> update($arr);   
            // 将用户名存入session
            $username = $data['user_phone'] ? $data['user_phone'] : $data['user_email'];
            session(['username'=>$username]);
            session(['id'=>$res['id']]);		
    		// 跳转页面到主页
            // 轮播图数据
            $data = DB::table('user_photo') ->where('photo_status','1')->get();
    		return view('welcome',['data'=>$data]);
    	}else{
    		return back() -> withInput() -> with('error','抱歉:用户名或密码错误');
    	}
    	
    }

    public function getExit(Request $request){
        $request -> session() -> flush();
        return redirect('/home/login');
    }
}
